<template>
  <div class="min-h-screen flex items-center justify-center bg-gray-50 p-4">
    <div class="w-full max-w-md">
      <div class="bg-white rounded-2xl shadow-xl overflow-hidden transform transition-all duration-300 hover:shadow-2xl">
        <div class="p-6 sm:p-8">
          <div class="flex justify-center mb-8">
            <div class="w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center">
              <i class="fa fa-shopping-bag text-primary text-2xl"></i>
            </div>
          </div>
          
          <h2 class="text-center text-2xl font-bold text-gray-900 mb-6">
            欢迎登录电商系统
          </h2>
          
          <form @submit.prevent="handleLogin" class="space-y-6">
            <div class="space-y-2">
              <label for="username" class="block text-sm font-medium text-gray-700">账号</label>
              <div class="relative">
                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <i class="fa fa-user text-gray-400"></i>
                </div>
                <input 
                  type="text" 
                  id="username" 
                  v-model="form.username"
                  class="block w-full pl-10 pr-3 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all duration-200"
                  placeholder="请输入账号"
                  ref="usernameRef"
                  @blur="validateUsername"
                >
              </div>
              <div v-if="errors.username" class="text-red-500 text-sm">
                {{ errors.username }}
              </div>
            </div>
            
            <div class="space-y-2">
              <label for="password" class="block text-sm font-medium text-gray-700">密码</label>
              <div class="relative">
                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <i class="fa fa-lock text-gray-400"></i>
                </div>
                <input 
                  type="{{ showPassword ? 'text' : 'password' }}" 
                  id="password" 
                  v-model="form.password"
                  class="block w-full pl-10 pr-10 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all duration-200"
                  placeholder="请输入密码"
                  @blur="validatePassword"
                >
                <div class="absolute inset-y-0 right-0 pr-3 flex items-center">
                  <button 
                    type="button" 
                    class="text-gray-400 hover:text-gray-600 focus:outline-none"
                    @click="showPassword = !showPassword"
                  >
                    <i class="{{ showPassword ? 'fa fa-eye-slash' : 'fa fa-eye' }}"></i>
                  </button>
                </div>
              </div>
              <div v-if="errors.password" class="text-red-500 text-sm">
                {{ errors.password }}
              </div>
            </div>
            
            <div class="space-y-2">
              <label for="captcha" class="block text-sm font-medium text-gray-700">验证码</label>
              <div class="flex space-x-3">
                <div class="relative flex-1">
                  <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <i class="fa fa-shield text-gray-400"></i>
                  </div>
                  <input 
                    type="text" 
                    id="captcha" 
                    v-model="form.captcha"
                    class="block w-full pl-10 pr-3 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all duration-200"
                    placeholder="请输入验证码"
                    @blur="validateCaptcha"
                  >
                </div>
                <div class="flex-shrink-0 w-32 h-12 bg-gray-100 rounded-lg flex items-center justify-center cursor-pointer" @click="refreshCaptcha">
                  <span class="text-xs text-gray-500">点击刷新</span>
                </div>
              </div>
              <div v-if="errors.captcha" class="text-red-500 text-sm">
                {{ errors.captcha }}
              </div>
            </div>
            
            <div class="flex items-center justify-between">
              <div class="flex items-center">
                <input 
                  id="remember" 
                  type="checkbox" 
                  v-model="rememberMe"
                  class="w-4 h-4 text-primary focus:ring-primary border-gray-300 rounded"
                >
                <label for="remember" class="ml-2 block text-sm text-gray-700">
                  记住密码
                </label>
              </div>
              <div class="text-sm">
                <a href="#" class="font-medium text-primary hover:text-primary/80 transition-colors">
                  忘记密码?
                </a>
              </div>
            </div>
            
            <button 
              type="submit"
              class="w-full flex justify-center items-center py-3 px-4 border border-transparent rounded-lg font-medium text-white bg-gradient-to-r from-primary to-primary/80 hover:shadow-lg hover:shadow-primary/20 transform hover:scale-[1.02] transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary"
              :disabled="isLoading"
            >
              {{ isLoading ? '登录中...' : '登录' }}
              <span v-if="isLoading" class="ml-2 animate-spin">
                <i class="fa fa-spinner"></i>
              </span>
            </button>
            
            <p class="text-center text-sm text-gray-600">
              还没有账号? 
              <a href="#" class="font-medium text-primary hover:text-primary/80 transition-colors">
                立即注册
              </a>
            </p>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watchEffect } from 'vue';
import { useRouter } from 'vue-router';

// 导入 Tailwind 配置中的颜色
const primaryColor = getComputedStyle(document.documentElement).getPropertyValue('--tw-color-primary');

// 表单数据
const form = reactive({
  username: '',
  password: '',
  captcha: ''
});

// 错误信息
const errors = reactive({
  username: '',
  password: '',
  captcha: ''
});

// 状态管理
const usernameRef = ref(null);
const isLoading = ref(false);
const showPassword = ref(false);
const rememberMe = ref(false);
const router = useRouter();

// 生命周期钩子
onMounted(() => {
  // 自动聚焦到账号输入框
  usernameRef.value.focus();
  
  // 检查本地存储中是否有记住的密码
  const savedCredentials = localStorage.getItem('savedCredentials');
  if (savedCredentials) {
    const { username, password } = JSON.parse(savedCredentials);
    form.username = username;
    form.password = password;
    rememberMe.value = true;
  }
  
  // 刷新验证码
  refreshCaptcha();
});

// 监听记住密码状态
watchEffect(() => {
  if (!rememberMe.value) {
    localStorage.removeItem('savedCredentials');
  }
});

// 表单验证函数
const validateUsername = () => {
  if (!form.username.trim()) {
    errors.username = '账号不能为空';
  } else if (form.username.length < 3) {
    errors.username = '账号长度不能少于3个字符';
  } else {
    errors.username = '';
  }
};

const validatePassword = () => {
  if (!form.password) {
    errors.password = '密码不能为空';
  } else if (form.password.length < 6) {
    errors.password = '密码长度不能少于6个字符';
  } else {
    errors.password = '';
  }
};

const validateCaptcha = () => {
  if (!form.captcha) {
    errors.captcha = '验证码不能为空';
  } else if (form.captcha.length !== 4) {
    errors.captcha = '验证码长度必须为4位';
  } else {
    errors.captcha = '';
  }
};

// 刷新验证码
const refreshCaptcha = () => {
  // 这里只是模拟刷新验证码，实际项目中需要调用后端接口
  console.log('刷新验证码');
};

// 登录处理函数
const handleLogin = async () => {
  // 先进行表单验证
  validateUsername();
  validatePassword();
  validateCaptcha();
  
  // 检查是否有错误
  if (errors.username || errors.password || errors.captcha) {
    return;
  }
  
  // 开始登录流程
  isLoading.value = true;
  
  try {
    // 模拟登录请求
    await new Promise(resolve => setTimeout(resolve, 1500));
    
    // 模拟登录成功
    if (form.username === 'test' && form.password === '123456' && form.captcha === '1234') {
      // 保存登录状态
      localStorage.setItem('isLoggedIn', 'true');
      
      // 如果勾选了记住密码，则保存到本地存储
      if (rememberMe.value) {
        localStorage.setItem('savedCredentials', JSON.stringify({
          username: form.username,
          password: form.password
        }));
      }
      
      // 跳转到首页
      router.push('/');
      
      // 显示登录成功提示
      alert('登录成功！');
    } else {
      // 登录失败
      let errorMessage = '登录失败';
      if (form.username !== 'test') errorMessage = '账号不存在';
      else if (form.password !== '123456') errorMessage = '密码错误';
      else if (form.captcha !== '1234') errorMessage = '验证码错误';
      
      alert(errorMessage);
      
      // 刷新验证码
      refreshCaptcha();
      form.captcha = '';
    }
  } catch (error) {
    console.error('登录错误:', error);
    alert('登录过程中发生错误，请稍后再试');
  } finally {
    isLoading.value = false;
  }
};
</script>

<style scoped>
/* 导入字体 */
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');

/* 设置基础样式 */
:root {
  --tw-color-primary: #165DFF;
  --font-family-sans: 'Inter', system-ui, sans-serif;
}

/* 自定义动画 */
@keyframes shake {
  0%, 100% { transform: translateX(0); }
  10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
  20%, 40%, 60%, 80% { transform: translateX(5px); }
}

.shake {
  animation: shake 0.5s ease-in-out;
}
</style>    